package zb.WX.service.account;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import zb.WX.bean.account.Qrcode;
import zb.WX.bean.account.QrcodeActionInfo;
import zb.WX.bean.account.QrcodeSence;
import zb.WX.util.AccessTokenSaveUtil;
import zb.WX.util.GlobalVar;
import zb.WX.util.HttpsUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


/**
 * 获取二维码
 *
 * @author Administrator
 */
public class QrcodeService {
    /*
     * 用ticket换取二维码:
     * 1.依赖于QrcodeService.getTicket()方法
     * 2.这里只演示临时二维码
     */

    public String getQrcode(String expire_seconds, String action_name, String scene_id) {
        String ticket = new QrcodeService().getTicket(expire_seconds, action_name, scene_id);
        String urlStr = GlobalVar.GET_QRCODE.replace("TICKET", ticket);

        String result = HttpsUtil.getHttpsToJson(urlStr, null);

        return result;
    }


    /*
     * 获取二维码ticket
     */
    public String getTicket(String expire_seconds, String action_name, String scene_id) {
        String access_token = AccessTokenSaveUtil.getLocationAccesstonken();
        String urlStr = GlobalVar.TRANSITORY_QRCODE.replace("ACCESS_TOKEN", access_token);

        QrcodeSence sence = new QrcodeSence();
        sence.setScene_id(scene_id);

        QrcodeActionInfo actionInfo = new QrcodeActionInfo();
        actionInfo.setSence(sence);

        Qrcode qrcode = new Qrcode();
        qrcode.setExpire_seconds(expire_seconds);
        qrcode.setAction_name(action_name);
        qrcode.setAction_info(actionInfo);

        Gson gson = new Gson();
        String jsonStr = gson.toJson(qrcode);
        System.out.println("转化二维码ticket：" + jsonStr);

        String result = HttpsUtil.getHttpsToJson(urlStr, jsonStr);
        System.out.println("返回的二维码ticket：" + result);

        //将返回json数据转化为json对象，并提取出ticket
        JsonObject jsonObject = gson.fromJson(result, JsonObject.class);
        String ticketStr = jsonObject.get("ticket").toString().replace("\"", "");
        System.out.println("获取到的ticket:" + ticketStr);

        String ticket;
        try {
            ticket = URLEncoder.encode(ticketStr, "UTF-8");//根据文档要求进行URLEncoder处理
            return ticket;
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

    }

    public static void main(String[] args) {
        String ticket = new QrcodeService().getTicket("604800", "QR_SCENE", "1111121");
        //new QrcodeService().getQrcode("604800", "QR_SCENE", "1111");//输出的是一张图片
    }
}
